package app.map;

import android.content.Context;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.zejian.emotionkeyboard.utils.LogUtils;

import tools.AMapUtil;

/**
 * Created by ThinkPad on 2017/5/4.
 */

public class BasicMapPersenter implements AMap.OnCameraChangeListener,GeocodeSearch.OnGeocodeSearchListener {

    private BasicMapView view;
    private BasicMapModel model;

    private AMap aMap;
    private UiSettings mUiSettings;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    private GeocodeSearch geocoderSearch;

    public BasicMapPersenter(BasicMapView view){
        this.view = view;
        model = new BasicMapModel();
    }

    public String getCity(){
        return model.getCity();
    }

    public String getLongName(){
        return model.getLaddressname();
    }
    public String getShotname(){
        return model.getSaddressname();
    }
    public double getLongitude(){
        return model.getLatLng().longitude;
    }
    public double getLatitude(){
        return model.getLatLng().latitude;
    }
    /**
     * 初始化AMap对象
     */
    public void initMap(Context context,AMap amap) {
        if (aMap == null) {
            aMap = amap;
        }
        aMap.showMapText(true);
        aMap.showBuildings(true);
        aMap.setOnCameraChangeListener(this);
        mUiSettings = aMap.getUiSettings();
        geocoderSearch = new GeocodeSearch(context);
        geocoderSearch.setOnGeocodeSearchListener(this);
        mUiSettings
                .setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_CENTER);// 设置地图logo显示在底部居中
    }

    /**
     * 初始化定位
     */
    public void initLocation(Context applicationContext){
        //初始化client
        locationClient = new AMapLocationClient(applicationContext);
        locationOption = model.getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 销毁定位
     */
    public void destroyLocation(){
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    /**
     * 开始定位
     */
    public void startLocation(){
//		locationClient.setLocationOption(locationOption);
        locationClient.startLocation();
    }

    /**
     * 停止定位
     */
    public void stopLocation(){
        locationClient.stopLocation();
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                String result = model.getLocationInfor(location);
                LogUtils.e(result);
                model.setCity(location.getCity());
                setLocationToMap(new LatLng(location.getLatitude(), location.getLongitude()));
            } else {
                LogUtils.e("定位失败，loc is null");
            }
        }
    };

    public void setLocationToMap(LatLng latLng){
        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                latLng, 17, 0, 0)));
        aMap.clear();
        aMap.addMarker(new MarkerOptions().position(latLng)
                .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
    }
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        LatLng latLng = cameraPosition.target;
        if(isBack){
            view.showAddressName(model.getLaddressname(), model.getSaddressname());
            isBack = false;
        }else {
            getAddress(new LatLonPoint(latLng.latitude, latLng.longitude));
        }
    }

    private boolean isBack = false;
    /**
     * 响应地理编码
     */
    public void getLatlon(final String name) {
        GeocodeQuery query = new GeocodeQuery(name, model.getCity());// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
        geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
    }
    /**
     * 地理编码查询回调
     */
    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {

        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getGeocodeAddressList() != null
                    && result.getGeocodeAddressList().size() > 0) {
                isBack = true;
                GeocodeAddress address = result.getGeocodeAddressList().get(0);
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));
                model.setLatLng(new LatLng(address.getLatLonPoint().getLatitude(), address.getLatLonPoint().getLongitude()));
            } else {
                view.showToast("对不起，没有搜索到相关数据！");
            }
        } else {
            view.showToast(rCode);
        }
    }

    /**
     * 响应逆地理编码
     */
    public void getAddress(final LatLonPoint latLonPoint) {
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
                GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
        model.setLatLng(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()));
    }
    /**
     * 逆地理编码回调
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                model.setLaddressname(result.getRegeocodeAddress().getFormatAddress());
                model.setSaddressname(result.getRegeocodeAddress().getDistrict());
//                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
//                        AMapUtil.convertToLatLng(latLonPoint), 15));
//                regeoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint));
                view.showAddressName(model.getLaddressname(), model.getSaddressname());
            } else {
                view.showToast("对不起，没有搜索到相关数据！");
            }
        } else {
            view.showToast(rCode);
        }
    }

    public void setAddressName(String laddressName, String saddressName) {
        model.setLaddressname(laddressName);
        model.setSaddressname(saddressName);
    }
}
